/*
 * @Author: huangyingli
 * @Date: 2023-02-27 11:45:10
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-28 13:58:26
 * @Description:
 */
import loadable from 'loadable-components';
import { useRouter } from 'next/router';

function toLow(name) {
  let first = name[0];
  first = String.prototype.toLowerCase.call(first);
  return first + name.slice(1);
}
export default function Slug(props) {
  // 循环所有组件
  // 根据组件名构建标签
  // 传入组件数据
  let components = props?.components || [];

  function getData(name) {
    let data = props?.componentsData[toLow(name)];
    console.log('dat', data);
    return data || [];
  }
  return (
    <>
      {components.map((component) => {
        let Component = loadable(() => import(`@/components/${component}.js`));
        return (
          <Component
            key={component}
            value={(getData(component) || [])[0]}
            columnList={props?.columnList}
          ></Component>
        );
      })}
    </>
  );
}

export async function getStaticPaths() {
  // 获取栏目层级

  const res = await fetch(`http://127.0.0.1:8089/columnRouteAll`);

  const routes = await res.json();
  const paths = routes.map((route) => ({
    params: { slug: route },
  }));

  return { paths, fallback: true };
}

export async function getStaticProps({ params }) {
  // 通过 props 参数向页面传递博文的数据
  let route = params.slug.slice(-1)[0];
  // console.log('route', route);
  const columnRes = await fetch(
    `http://localhost:8089/columnIdByRoute?route=${route}`
  );

  const column = await columnRes.json();
  console.log('column', column.data);
  const res = await fetch(
    `http://localhost:8089/contentDataAll?columnId=${column.data.id}`
  );
  const componentsData = await res.json();
  console.log('componentsData', componentsData);

  const components = Object.keys(componentsData.data).map((c) => {
    let first = c[0];
    first = String.prototype.toUpperCase.call(first);
    return first + c.slice(1);
  });

  const columnList = await (
    await fetch('http://localhost:8089/columnList', { method: 'post' })
  ).json();
  return {
    props: {
      params,
      componentsData: componentsData.data,
      columnList: columnList.data,
      components: components,
    },
    revalidate: 1,
  };
}
